import logging
import queue
from time import sleep

from messenger.apps.vmachine.handlers import CreateVmachine
from messenger.utils.response_util import RET



class Task(object):
    def __init__(self, priority_queue_job_param):
        self._priority = priority_queue_job_param.priority
        self._job_type = priority_queue_job_param.job_type
        self._time = priority_queue_job_param.sub_time
        self.body = priority_queue_job_param.body
        self.auth = priority_queue_job_param.auth

    def __str__(self):
        return "Task(priority={}, name={}, time={}).".format(self._priority, self._job_type, self._time)

    def __lt__(self, other):
        if self._priority != other._priority:
            return self._priority < other._priority
        else:
            return self._time < other._time


class JobQueue():
    instance = None
    init_flat = False

    def __new__(cls, *args, **kwargs):
        if cls.instance is None:
            cls.instance = super().__new__(cls)
        return cls.instance

    def __init__(self):
        if self.init_flat is True:
            return
        self.queue = queue.PriorityQueue()
        self.init_flat = True


tsq = JobQueue().queue


class CreateVmachineInCelery(CreateVmachine):
    def __init__(self, auth, body):
        super().__init__(auth, body)

    @property
    def logger(self):
        return logging


def consume_job():
    num = 0
    while True:
        num += 1
        if tsq.empty():
            if num / 10 == 0:
                logging.info("empty queue,waiting for job..")
            sleep(5)
        else:
            task = tsq.get()
            while True:
                _resp = CreateVmachineInCelery(task.auth, task.body).install()
                if _resp.get("error_code") == RET.OK:
                    tsq.task_done()
                    break
                else:
                    logging.error(_resp.get("error_msg"))
